#include "buffersocket.h"

BufferSocket :: BufferSocket( int connfd ) : m_tSocket( connfd )
{
}

BufferSocket :: ~BufferSocket()
{}

int BufferSocket :: ClearReadBuffer()
{
	return m_tReadBuffer.Clear();
}

int BufferSocket :: ClearWriteBuffer()
{
	return m_tWriteBuffer.Clear();
}

int BufferSocket ::  ReadToBuffer()
{
	int iGetLen = -1;
	char tempbuf[TEMPLEN] = {0};

	iGetLen = m_tSocket.Read( tempbuf, TEMPLEN );
	if ( iGetLen > 0 )
	{
		m_tReadBuffer.Append( tempbuf, iGetLen );
	}
	return iGetLen;
}

//return 0 or -1
int BufferSocket :: ReadToBufferEx()
{
	int n = -1;
	while ( (n = this->ReadToBuffer())> 0 )
	{}
	return n;
}

int BufferSocket :: WriteFromBuffer()
{
	return m_tSocket.Write( m_tWriteBuffer.GetByteBuffer(), 
			m_tWriteBuffer.GetLimit());
}

int BufferSocket :: WriteFromBufferEx()
{
	int tmp = -1, sendlen = m_tWriteBuffer.GetOffset();
	int ret = -1;

	for (;;) 
	{
		if ( m_tWriteBuffer.GetRemainLen() > 0 )
		{
			tmp = m_tSocket.Write( m_tWriteBuffer.GetRemainByteBuffer(),
					m_tWriteBuffer.GetRemainLen() ); 
			if ( tmp >= 0 )
			{
				sendlen += tmp;
				m_tWriteBuffer.SetOffset( sendlen );
			}
			else//error
			{
				break;
			}
		}
		else//all buffer sent
		{
			ret = 0;
			break;
		}
	}

	return ret;
}

Buffer * BufferSocket :: GetReadBuffer()
{
	return &m_tReadBuffer;
}

Buffer * BufferSocket :: GetWriteBuffer()
{
	return &m_tWriteBuffer;
}

int BufferSocket :: GetFd()
{
	return m_tSocket.GetSocketFD();
}



